//
//  PlaySongViewController.m
//  Mecca
//
//  Created by Ryan Enguero on 5/26/14.
//  Copyright (c) 2014 TapDash Heuristics. All rights reserved.
//

#import "PlaySongViewController.h"

#import "ParserClass.h"

#import "AudioPlayManager.h"

#import <AVFoundation/AVFoundation.h>

#import "MusicDatabase.h"

#import "AppDelegate.h"

#import "Songs.h"

#import "DownloadedSongs.h"

#import "PostClass.h"

#import "JsonClass.h"

#import "Constant.h"

#import "UserDetails.h"

#import "StarRatingView.h"

#import "Album.h"

#import "MACircleProgressIndicator.h"

#import "PlaySongTableViewCell.h"

#import "ParserClass.h"

#import "Comments.h"

#import "TopDownloaded.h"

#import "Favorites.h"

#import "LocalPlayerClass.h"

#import <FacebookSDK/FacebookSDK.h>

#import "PlayListData.h"

#import "DownloadedSongs.h"

#import "ListenedSongs.h"

#define kLabelAllowance 40.0f
#define kStarViewHeight 20.0f
#define kStarViewWidth 150.0f
#define kLeftPadding 4.0f


@interface PlaySongViewController ()
{
    
    
    NSURLConnection *theConnection;
    NSMutableData *receivedData;
    NSURL *audioFileURL;
    NSData *dataFromCore;
    float start;
    UITextField *rateData;
    int *rates;
    
    NSString *numberOfrate;
    NSString *kbSize;
    NSMutableData* bufferToSend;

    NSString *songName;

    
    NSMutableArray *arrData;
    
    int value;

}
@property (strong, nonatomic) NSData *dataSong;

@property(strong, nonatomic) NSTimer *resumeTimer;
@property(strong, nonatomic) NSTimer *pauseTimer;
@property(strong, nonatomic) NSTimer *startTimer;
@property(strong, nonatomic) NSTimer *stopTimer;
@property(strong, nonatomic) NSTimer *revertTimer;
@property (weak, nonatomic) IBOutlet UISlider *processSlider;

- (IBAction)processSliderValueChanged:(id)sender;
- (IBAction)sliderTouchDown:(id)sender;
- (IBAction)sliderTouchInside:(id)sender;
- (IBAction)sliderTouchUpOutside:(id)sender;

- (IBAction)play:(id)sender;
- (IBAction)stop:(id)sender;
- (IBAction)resume:(id)sender;
- (IBAction)pause:(id)sender;
@property (weak, nonatomic) IBOutlet UITextField *statusText;

@property (strong, nonatomic) IBOutlet UIButton *shareOGStoryWithShareDialogButton;

@end

@implementation PlaySongViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    
    [super viewDidLoad];
    
    [self disableDownloadBtn];
    
    
    
    self.downloadQueue = [[NSMutableArray alloc] init];
    
    [((AppDelegate*)[[UIApplication sharedApplication] delegate]) fetchListenedSong];
    
    MACircleProgressIndicator *appearance = [MACircleProgressIndicator appearance];
    
    // The color property sets the actual color of the procress circle (how
    // suprising ;) )
    appearance.color = [UIColor redColor];
    
    // Use the strokeWidth property to set the width of the
    // circle stroke excplicitly.
    appearance.strokeWidth = 2.0;
    
    self.largeProgressIndicator.value = 0;
    
    UIImage *buttonImage = [UIImage imageNamed:@"userProfile.png"];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:buttonImage forState:UIControlStateNormal];
    button.frame = CGRectMake(0, 100, buttonImage.size.width, buttonImage.size.height);
    [button addTarget:self action:@selector(userProfile) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *customBarItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.leftBarButtonItem = customBarItem;
    
    [self.tblComment setBackgroundColor:[UIColor blackColor]];
    
    // Do any additional setup after loading the view from its nib.
    
    NSInteger idx = [[ParserClass sharedItems] idxCount];
    
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setInteger:idx forKey:@"idxData"];
    [defaults synchronize];
    
    Songs *song = [[ParserClass sharedItems] songDetails][idx];
    TopDownloaded *topDl = [[ParserClass sharedItems] topDownloadeds][idx];
    Favorites *topFavorites = [[ParserClass sharedItems] topFavorites][idx];
    
    if (![[song likes] isEqualToString:@"0"]) {
        [self.likeBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    }

    self.likeCount.text = [song likes];
    
    int i = [[[ParserClass sharedItems] fileSizeSong] intValue];
    
    NSLog(@"filesize = %i", i / 100);

    [self setImageString:[NSString stringWithFormat:@"http://192.185.93.102/~boomeran/backend-panel/%@",[[ParserClass sharedItems] imgAlbum]]];
    
    NSLog(@"Song name = %@",[song songName]);
    
    songName = [song songName];
    
    int likers = [[song ratings] intValue];
    
    NSLog(@"Test Likes %@", [song ratings]);
    
    StarRatingView* starViewNoLabel = [[StarRatingView alloc]initWithFrame:CGRectMake(55, 421, 45, 8) andRating:likers withLabel:NO animated:YES];
    
    [starViewNoLabel setUserInteractionEnabled:NO];
    
    [self.view addSubview:starViewNoLabel];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(rateView)];
    
    tap.numberOfTapsRequired = 1;
    
    [starViewNoLabel addGestureRecognizer:tap];
    
    [self.btnPlay setHidden:YES];
    
    [self.tabBarController.tabBar setHidden:YES];
    
    NSLog(@"URL = %@", [[ParserClass sharedItems] urlSong]);
    
    
    self.handle = [NSFileHandle fileHandleForUpdatingAtPath:[[ParserClass sharedItems] songPreview]];
    
    if ([[[ParserClass sharedItems] songPreview] isEqualToString:@"http://192.185.93.102/~boomeran/backend-panel/"]) {
        [[AudioPlayManager shareObject] setAudioURL:[[ParserClass sharedItems] urlSong] playImmediately:YES isLocal:[[NSURL URLWithString:[[ParserClass sharedItems] songPreview]] isFileURL]];
    }else{
    
    [[AudioPlayManager shareObject] setAudioURL:[[ParserClass sharedItems] songPreview] playImmediately:YES isLocal:[[NSURL URLWithString:[[ParserClass sharedItems] songPreview]] isFileURL]];
    }
    
    
    [self settingUpPlayer];
//    if ([[[ParserClass sharedItems] songListened] count] == 0) {
//        
//        value = 1;
//        
//        NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
//        [defaultCenter addObserver:self selector:@selector(handleProgressUpdate) name:AudioPlayManagerProgressUpdated object:nil];
//        
//        [defaultCenter addObserver:self selector:@selector(handleStopped) name:AudioPlayManagerStopped object:nil];
//        [defaultCenter addObserver:self selector:@selector(handlePlaying) name:AudioPlayManagerPlaying object:nil];
//        [defaultCenter addObserver:self selector:@selector(handleLoading) name:AudioPlayManagerLoading object:nil];
//        [defaultCenter addObserver:self selector:@selector(handleError) name:AudioPlayManagerError object:nil];
//        [defaultCenter addObserver:self selector:@selector(handlePause) name:AudioPlayManagerPaused object:nil];
//        [defaultCenter addObserver:self selector:@selector(handleFinished) name:AudioPlayManagerPlayingFinished object:nil];
//    }else{
//    
//    
//    for (int i = 0; i < [[[ParserClass sharedItems] songListened] count]; i++) {
//        
//        ListenedSongs *listenedSongs = [[ParserClass sharedItems] songListened][i];
//        
//        if ([[song songName] isEqualToString:[listenedSongs songName]] || [[topDl songName] isEqualToString:[listenedSongs songName]] || [[topFavorites songName] isEqualToString:[listenedSongs songName]]) {
//            
////            self.processSlider.maximumValue = 30.0f;
//            value = 2;
//            NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
//            [defaultCenter addObserver:self selector:@selector(handleProgressUpdatePreview) name:AudioPlayManagerProgressUpdated object:nil];
//            
//            [defaultCenter addObserver:self selector:@selector(handleStopped) name:AudioPlayManagerStopped object:nil];
//            [defaultCenter addObserver:self selector:@selector(handlePlaying) name:AudioPlayManagerPlaying object:nil];
//            [defaultCenter addObserver:self selector:@selector(handleLoading) name:AudioPlayManagerLoading object:nil];
//            [defaultCenter addObserver:self selector:@selector(handleError) name:AudioPlayManagerError object:nil];
//            [defaultCenter addObserver:self selector:@selector(handlePause) name:AudioPlayManagerPaused object:nil];
//            [defaultCenter addObserver:self selector:@selector(handleFinishedPreview) name:AudioPlayManagerPlayingFinished object:nil];
//            
//         break;
//            
//        }
//        
//        
//        
//        else{
//        
//            value = 1;
//            
//            NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
//            [defaultCenter addObserver:self selector:@selector(handleProgressUpdate) name:AudioPlayManagerProgressUpdated object:nil];
//            
//            [defaultCenter addObserver:self selector:@selector(handleStopped) name:AudioPlayManagerStopped object:nil];
//            [defaultCenter addObserver:self selector:@selector(handlePlaying) name:AudioPlayManagerPlaying object:nil];
//            [defaultCenter addObserver:self selector:@selector(handleLoading) name:AudioPlayManagerLoading object:nil];
//            [defaultCenter addObserver:self selector:@selector(handleError) name:AudioPlayManagerError object:nil];
//            [defaultCenter addObserver:self selector:@selector(handlePause) name:AudioPlayManagerPaused object:nil];
//            [defaultCenter addObserver:self selector:@selector(handleFinished) name:AudioPlayManagerPlayingFinished object:nil];
//            
//            
//            
//            
//        }
//    }
//        
//        
//
//        
//        
//   }
   
    
    
    
    
    
    
    [self commentLoading];
}

- (void)settingUpPlayer{
    
    NSInteger idx = [[ParserClass sharedItems] idxCount];
    Songs *song = [[ParserClass sharedItems] songDetails][idx];
    TopDownloaded *topDl = [[ParserClass sharedItems] topDownloadeds][idx];
    Favorites *topFavorites = [[ParserClass sharedItems] topFavorites][idx];

    if ([[[ParserClass sharedItems] songListened] count] == 0) {
        
        value = 1;
        
        NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
        [defaultCenter addObserver:self selector:@selector(handleProgressUpdate) name:AudioPlayManagerProgressUpdated object:nil];
        
        [defaultCenter addObserver:self selector:@selector(handleStopped) name:AudioPlayManagerStopped object:nil];
        [defaultCenter addObserver:self selector:@selector(handlePlaying) name:AudioPlayManagerPlaying object:nil];
        [defaultCenter addObserver:self selector:@selector(handleLoading) name:AudioPlayManagerLoading object:nil];
        [defaultCenter addObserver:self selector:@selector(handleError) name:AudioPlayManagerError object:nil];
        [defaultCenter addObserver:self selector:@selector(handlePause) name:AudioPlayManagerPaused object:nil];
        [defaultCenter addObserver:self selector:@selector(handleFinished) name:AudioPlayManagerPlayingFinished object:nil];
    }else{
        
        
        for (int i = 0; i < [[[ParserClass sharedItems] songListened] count]; i++) {
            
            ListenedSongs *listenedSongs = [[ParserClass sharedItems] songListened][i];
            
            if ([[song songName] isEqualToString:[listenedSongs songName]] || [[topDl songName] isEqualToString:[listenedSongs songName]] || [[topFavorites songName] isEqualToString:[listenedSongs songName]]) {
                
                //            self.processSlider.maximumValue = 30.0f;
                value = 2;
                NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
                [defaultCenter addObserver:self selector:@selector(handleProgressUpdatePreview) name:AudioPlayManagerProgressUpdated object:nil];
                
                [defaultCenter addObserver:self selector:@selector(handleStopped) name:AudioPlayManagerStopped object:nil];
                [defaultCenter addObserver:self selector:@selector(handlePlaying) name:AudioPlayManagerPlaying object:nil];
                [defaultCenter addObserver:self selector:@selector(handleLoading) name:AudioPlayManagerLoading object:nil];
                [defaultCenter addObserver:self selector:@selector(handleError) name:AudioPlayManagerError object:nil];
                [defaultCenter addObserver:self selector:@selector(handlePause) name:AudioPlayManagerPaused object:nil];
                [defaultCenter addObserver:self selector:@selector(handleFinishedPreview) name:AudioPlayManagerPlayingFinished object:nil];
                
                break;
                
            }
            
            
            
            else{
                
                value = 1;
                
                NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
                [defaultCenter addObserver:self selector:@selector(handleProgressUpdate) name:AudioPlayManagerProgressUpdated object:nil];
                
                [defaultCenter addObserver:self selector:@selector(handleStopped) name:AudioPlayManagerStopped object:nil];
                [defaultCenter addObserver:self selector:@selector(handlePlaying) name:AudioPlayManagerPlaying object:nil];
                [defaultCenter addObserver:self selector:@selector(handleLoading) name:AudioPlayManagerLoading object:nil];
                [defaultCenter addObserver:self selector:@selector(handleError) name:AudioPlayManagerError object:nil];
                [defaultCenter addObserver:self selector:@selector(handlePause) name:AudioPlayManagerPaused object:nil];
                [defaultCenter addObserver:self selector:@selector(handleFinished) name:AudioPlayManagerPlayingFinished object:nil];
                
                
                
                
            }
        }
        
        
        
        
        
    }


}

- (void)disableDownloadBtn{
    
    
    [((AppDelegate*)[[UIApplication sharedApplication] delegate]) fetchMusicDataFromCoreData];
    
    NSInteger idx = [[ParserClass sharedItems] idxCount];
    Songs *song = [[ParserClass sharedItems] songDetails][idx];
    TopDownloaded *topDL = [[ParserClass sharedItems] topDownloadeds][idx];
    Favorites *favorite = [[ParserClass sharedItems] topFavorites][idx];
    
    
    for (int i = 0; i < [[[ParserClass sharedItems] downloadedSongs] count]; i++) {
      
        DownloadedSongs *downloadedSongs = [[ParserClass sharedItems] downloadedSongs][i];
        
        if ([[[ParserClass sharedItems] type] isEqualToString:@"Songs"]) {
            
            if ([[song songName] isEqualToString:[downloadedSongs songName]]) {
                
                self.downloadBtn.enabled = NO;
                break;
                
            }else{
                
                self.downloadBtn.enabled = YES;
            }
        }else if ([[[ParserClass sharedItems] type] isEqualToString:@"TopDownloads"]) {
            
            if ([[topDL songName] isEqualToString:[downloadedSongs songName]]) {
                
                self.downloadBtn.enabled = NO;
                break;
                
            }else{
                
                self.downloadBtn.enabled = YES;
            }
        }else if ([[[ParserClass sharedItems] type] isEqualToString:@"Favorites"]) {
            
            if ([[favorite songName] isEqualToString:[downloadedSongs songName]]) {
                
                self.downloadBtn.enabled = NO;
                break;
                
            }else{
                
                self.downloadBtn.enabled = YES;
            }
        }
        
        

    }
}

- (void)commentLoading{

    NSInteger idx = [[ParserClass sharedItems] idxCount];
    
    TopDownloaded *topDL = [[ParserClass sharedItems] topDownloadeds][idx];
    
    Favorites *favorite = [[ParserClass sharedItems] topFavorites][idx];
    
    Songs *song = [[ParserClass sharedItems] songDetails][idx];
    
    dispatch_async(kBgQueue, ^{
        
        if (!([song idSong] == nil)) {
            NSData *data = [[PostClass sharedItems] songViewComment:[song idSong]];
            
            [self performSelectorOnMainThread:@selector(fetchedDataSongComment:)
                                   withObject:data waitUntilDone:YES];
        }else if (!([topDL songID] == nil)) {
        
            NSData *data = [[PostClass sharedItems] songViewComment:[topDL songID]];
            
            [self performSelectorOnMainThread:@selector(fetchedDataSongComment:)
                                   withObject:data waitUntilDone:YES];
        }else{
        
            NSData *data = [[PostClass sharedItems] songViewComment:[favorite songID]];
            
            [self performSelectorOnMainThread:@selector(fetchedDataSongComment:)
                                   withObject:data waitUntilDone:YES];
            
        }
        
        
        
    });
    
    

}

- (void)rateView{

    NSLog(@"Rate");
    UIAlertView *av = [[UIAlertView alloc]initWithTitle:@"Rate" message:@"Please rate by 1 - 5" delegate:self cancelButtonTitle:nil otherButtonTitles:@"Rate",@"Cancel", nil];
    
    av.alertViewStyle = UIAlertViewStylePlainTextInput;
    
    rateData = [av textFieldAtIndex:0];
    
    numberOfrate = rateData.text;
    
    [av show];

}



- (void)fetchedDataSongComment:(NSData *)responseData{

    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:nil];
    
    [[ParserClass sharedItems] songComment:json];
    
    [self.tblComment reloadData];
    
    NSLog(@"Song Comments = %@", json);


}


-(void)userProfile{
    NSLog(@"User Profile");
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void) viewWillDisappear:(BOOL)animated
{
    [_pauseTimer invalidate];
    [_startTimer  invalidate];
    [_stopTimer  invalidate];
    [_revertTimer invalidate];
}



- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    //[[AudioPlayManager shareObject] start];
    
}


- (IBAction)processSliderValueChanged:(id)sender {
    
    if (value == 1) {
        CGFloat duration = [AudioPlayManager shareObject].duration;
        unsigned int currentTimeInsecond = duration * [_processSlider value];
        [[AudioPlayManager shareObject] seekToMinutes:currentTimeInsecond/60 Seconds:currentTimeInsecond%60];
        
        NSLog(@"current time = %i", currentTimeInsecond);
    }else if (value == 2){
    
        CGFloat duration = [AudioPlayManager shareObject].durationPreview;
        unsigned int currentTimeInsecond = duration * [_processSlider value];
        [[AudioPlayManager shareObject] seekToMinutes:currentTimeInsecond/60 Seconds:currentTimeInsecond%60];
        
        NSLog(@"current time = %i", currentTimeInsecond);
    }
    
    
}

- (IBAction)sliderTouchDown:(id)sender {
    
    [[AudioPlayManager shareObject] pause];
    
}

- (IBAction)sliderTouchInside:(id)sender {
    
    [[AudioPlayManager shareObject] resume];
    
}

- (IBAction)sliderTouchUpOutside:(id)sender {
    
    [[AudioPlayManager shareObject] resume];
    
}

- (IBAction)play:(id)sender {
    [self.btnPlay setHidden:YES];
    [self.btnPause setHidden:NO];
    [[AudioPlayManager shareObject] start];
}

- (IBAction)stop:(id)sender {
    [[AudioPlayManager shareObject] stop];
    
}

- (IBAction)resume:(id)sender {
    [[AudioPlayManager shareObject] resume];
}

- (IBAction)pause:(id)sender {
    [self.btnPause setHidden:YES];
    [self.btnPlay setHidden:NO];
    [[AudioPlayManager shareObject] pause];
    
}

-(void) handleProgressUpdate
{
    
//    start = [[AudioPlayManager shareObject] currentPlayedProgress];
    
    
    
    AudioPlayManager *ad = [AudioPlayManager shareObject];
    
    NSLog(@"processslider = %f", [[AudioPlayManager shareObject] currentPlayedProgress]);
    
    [self.lblPrevLimit setText:[NSString stringWithFormat:@"%d:0%d",ad.audioController.stream.duration.minute, ad.audioController.stream.duration.second]];
    
    [self.lblPrevStart setText:[NSString stringWithFormat:@"%d:0%d",ad.audioController.stream.currentTimePlayed.minute, ad.audioController.stream.currentTimePlayed.second]];
    
    if (ad.audioController.stream.currentTimePlayed.second >= 10) {
//        [self.lblPrevLimit setText:[NSString stringWithFormat:@"%d:%d",ad.audioController.stream.duration.minute, ad.audioController.stream.duration.second]];
        
        [self.lblPrevStart setText:[NSString stringWithFormat:@"%d:%d",ad.audioController.stream.currentTimePlayed.minute, ad.audioController.stream.currentTimePlayed.second]];
    }
    if (ad.audioController.stream.duration.second >= 10) {
         [self.lblPrevLimit setText:[NSString stringWithFormat:@"%d:%d",ad.audioController.stream.duration.minute, ad.audioController.stream.duration.second]];
    }
    
    
    
    self.processSlider.value = [[AudioPlayManager shareObject] currentPlayedProgress];
    
//    if (self.processSlider.value == 1) {
//        [[AudioPlayManager shareObject] stop];
//        [self.btnPause setHidden:YES];
//        [self.btnPlay setHidden:NO];
//
//    }
    
}

-(void) handleProgressUpdatePreview{

     AudioPlayManager *ad = [AudioPlayManager shareObject];
    
    NSLog(@"processslider preview = %f", [[AudioPlayManager shareObject] currentPlayedProgress]);
    
    self.processSlider.value = [[AudioPlayManager shareObject] currentPlayedProgressPreview];
    
    [self.lblPrevStart setText:[NSString stringWithFormat:@"%d:0%d",ad.audioController.stream.currentTimePlayed.minute, ad.audioController.stream.currentTimePlayed.second]];
    
    if (ad.audioController.stream.currentTimePlayed.second >= 10) {
        [self.lblPrevStart setText:[NSString stringWithFormat:@"%d:%d",ad.audioController.stream.currentTimePlayed.minute, ad.audioController.stream.currentTimePlayed.second]];
    }
    
    if (ad.audioController.stream.currentTimePlayed.second == 30) {
        [[AudioPlayManager shareObject] stop];
        [self.btnPause setHidden:YES];
        [self.btnPlay setHidden:NO];
    }
    
    [self.lblPrevLimit setText:@"0:30"];
}

-(void) handleStopped
{
    NSLog(@"Stopped");
    _statusText.text = @"Stopped";
    [[AudioPlayManager shareObject] stop];
    self.processSlider.value = 0.0;
//    [self.btnPause setHidden:YES];
//    [self.btnPlay setHidden:NO];
    
}

-(void) handleLoading
{
    NSLog(@"Loading");
    _statusText.text = @"Loading";
    
}

-(void) handlePause
{
    
    NSLog(@"Pause");
    _statusText.text = @"Pause";
    
    
}

-(void) handlePlaying
{
    NSLog(@"Playing");
    _statusText.text = @"Playing";
    
    
}

-(void) handleError
{
    NSLog(@"Error");
    _statusText.text = @"ERROR";
    
    
}

-(void) handleFinished
{
    NSLog(@"Finished");
    
    [self.btnPause setHidden:YES];
    [self.btnPlay setHidden:NO];
    
    NSInteger idx = [[ParserClass sharedItems] idxCount];
    Songs *song = [[ParserClass sharedItems] songDetails][idx];
    UserDetails *userDetails = [[ParserClass sharedItems] userDetails][0];
    TopDownloaded *topDL = [[ParserClass sharedItems] topDownloadeds][idx];
    Favorites *favorite = [[ParserClass sharedItems] topFavorites][idx];
    
        
        if ([[[ParserClass sharedItems] type] isEqualToString:@"Songs"]) {
            
            [((AppDelegate*)[[UIApplication sharedApplication] delegate]) getSongListenedWithName:[song songName] andUserID:[userDetails idUser]];
            [((AppDelegate*)[[UIApplication sharedApplication] delegate]) fetchListenedSong];
            
            [self settingUpPlayer];
            
         
        }else if ([[[ParserClass sharedItems] type] isEqualToString:@"TopDownloads"]) {
            
            [((AppDelegate*)[[UIApplication sharedApplication] delegate]) getSongListenedWithName:[topDL songName] andUserID:[userDetails idUser]];
            [((AppDelegate*)[[UIApplication sharedApplication] delegate]) fetchListenedSong];
            
            [self settingUpPlayer];
            
          
        }else if ([[[ParserClass sharedItems] type] isEqualToString:@"Favorites"]) {
            
            [((AppDelegate*)[[UIApplication sharedApplication] delegate]) getSongListenedWithName:[favorite songName] andUserID:[userDetails idUser]];
            [((AppDelegate*)[[UIApplication sharedApplication] delegate]) fetchListenedSong];
            
            [self settingUpPlayer];
            
           
        }
    
}

- (void) handleFinishedPreview{

    NSLog(@"Finished Preview");
}

- (IBAction)download:(id)sender {
    
    // Create the request.
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    NSInteger idx = [defaults integerForKey:@"idxData"];
    
    Songs *song = [[ParserClass sharedItems] songDetails][idx];
    
    TopDownloaded *topDL = [[ParserClass sharedItems] topDownloadeds][idx];
    
    Favorites *favorite = [[ParserClass sharedItems] topFavorites][idx];
    
    UserDetails *userDetails = [[ParserClass sharedItems] userDetails][0];
    
    
    
    if (!(song == nil)) {
        
    if ([[song price] isEqualToString:@"0"]) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Download" message:[NSString stringWithFormat:@"Do you want to download \"%@\" for free?", [song songName]] delegate:self cancelButtonTitle:nil otherButtonTitles:@"Yes", @"No", nil];
        alertView.tag = 1;
        [alertView show];
    }else if ([[song price] isEqualToString:@"Downloaded"]){
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Download" message:[NSString stringWithFormat:@"Do you want to download song \"%@\" again ?", [song songName]] delegate:self cancelButtonTitle:nil otherButtonTitles:@"Yes", @"No", nil];
        alertView.tag = 1;
        [alertView show];
    
    }else{
        
        
        if ([[userDetails credits] integerValue] < [[song price] integerValue]) {
            
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Failed" message:[NSString stringWithFormat:@"You don't have enough Boom points to download \"%@\"", [song songName]] delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil, nil];
            
            [alertView show];
        }else{
    
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Download" message:[NSString stringWithFormat:@"Do you want to download \"%@\" for %@BP?", [song songName], [song price]] delegate:self cancelButtonTitle:nil otherButtonTitles:@"Yes", @"No", nil];
        alertView.tag = 1;
        [alertView show];
        }
    
    }
            
        
    
    }else if (!(topDL == nil)){
        
        
       
        
        if ([[topDL price] isEqualToString:@"0"]) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Download" message:[NSString stringWithFormat:@"Do you want to download \"%@\" for free?", [topDL songName]] delegate:self cancelButtonTitle:nil otherButtonTitles:@"Yes", @"No", nil];
            alertView.tag = 1;
            [alertView show];
        }else if ([[topDL price] isEqualToString:@"Downloaded"]){
            
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Download" message:[NSString stringWithFormat:@"Do you want to download song \"%@\" again ?", [topDL songName]] delegate:self cancelButtonTitle:nil otherButtonTitles:@"Yes", @"No", nil];
            alertView.tag = 1;
            [alertView show];
            
        }else{
            
            if ([[userDetails credits] integerValue] < [[topDL price] integerValue]) {
                
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Failed" message:[NSString stringWithFormat:@"You don't have enough Boom points to download \"%@\"", [topDL songName]] delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil, nil];
                
                [alertView show];
                
            }else{
            
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Download" message:[NSString stringWithFormat:@"Do you want to download \"%@\" for %@BP?", [topDL songName], [topDL price]] delegate:self cancelButtonTitle:nil otherButtonTitles:@"Yes", @"No", nil];
            alertView.tag = 1;
            [alertView show];
            
        }
        }
    
    
    }else if (!(favorite == nil)){
        
      
        
            
    
        if ([[favorite price] isEqualToString:@"0"]) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Download" message:[NSString stringWithFormat:@"Do you want to download \"%@\" for free?", [favorite songName]] delegate:self cancelButtonTitle:nil otherButtonTitles:@"Yes", @"No", nil];
            alertView.tag = 1;
            [alertView show];
        }else if ([[favorite price] isEqualToString:@"Downloaded"]){
            
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Download" message:[NSString stringWithFormat:@"Do you want to download song \"%@\" again ?", [favorite songName]] delegate:self cancelButtonTitle:nil otherButtonTitles:@"Yes", @"No", nil];
            alertView.tag = 1;
            [alertView show];
            
        }else{
            
            if ([[userDetails credits] integerValue] < [[favorite price] integerValue]) {
                
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Failed" message:[NSString stringWithFormat:@"You don't have enough Boom points to download \"%@\"", [favorite songName]] delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil, nil];
                
                [alertView show];
                
            }else{
            
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Download" message:[NSString stringWithFormat:@"Do you want to download \"%@\" for %@BP?", [favorite songName], [favorite price]] delegate:self cancelButtonTitle:nil otherButtonTitles:@"Yes", @"No", nil];
            alertView.tag = 1;
            [alertView show];
            
        }
        }
    
    }
        
    
    
}



-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

    
    if (alertView.tag == 1) {
    
    if (buttonIndex == 0) {
        
        NSURLRequest *theRequest= [NSURLRequest requestWithURL:[NSURL URLWithString:[[ParserClass sharedItems] urlSong]]
                                                   cachePolicy:NSURLRequestUseProtocolCachePolicy
                                               timeoutInterval:60.0];
        
        

        
        theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
        
        
                if (theConnection) {
                    // Get Data
                    
                    receivedData = [NSMutableData data];
                    
                    NSLog(@"Received data final song = %@", receivedData);
                    
                    [self.downloadBtn setEnabled:NO];
                    
                    
                    
                    NSInteger idx = [[ParserClass sharedItems] idxCount];
                    
                    if ([[[ParserClass sharedItems] type] isEqualToString:@"Songs"]) {
                        
                        NSLog(@"Songs");
                  
                    Songs *song = [[ParserClass sharedItems] songDetails][idx];
                        
                    
                    [((AppDelegate*)[[UIApplication sharedApplication] delegate]) downloadingDataWithName:[song songName] andArtist:[[ParserClass sharedItems] artistName] andDuration:[song durations] andImage:[[ParserClass sharedItems] imgAlbum] andPrice:[song price] andSongID:[song idSong] andAlbumName:[[ParserClass sharedItems] albumName] andSongLyrics:[song songLyrics]];
                        
                    
                    [((AppDelegate*)[[UIApplication sharedApplication] delegate]) fetchDownloadingDataFromCoreData];
                        
                    }else if ([[[ParserClass sharedItems] type] isEqualToString:@"TopDownloads"]){
                        
                        NSLog(@"Top Downloads");
                        
                        TopDownloaded *topDL = [[ParserClass sharedItems] topDownloadeds][idx];
                        
                        [((AppDelegate*)[[UIApplication sharedApplication] delegate]) downloadingDataWithName:[topDL songName] andArtist:[[ParserClass sharedItems] artistName] andDuration:[topDL durations] andImage:[[ParserClass sharedItems] imgAlbum] andPrice:[topDL price] andSongID:[topDL songID] andAlbumName:[[ParserClass sharedItems] albumName] andSongLyrics:[topDL songLyrics]];
                        
                        [((AppDelegate*)[[UIApplication sharedApplication] delegate]) fetchDownloadingDataFromCoreData];
                    
                    }else if ([[[ParserClass sharedItems] type] isEqualToString:@"Favorites"]){
                        
                        NSLog(@"Favorites");
                        
                        Favorites *favorite = [[ParserClass sharedItems] topFavorites][idx];
                        
                        [((AppDelegate*)[[UIApplication sharedApplication] delegate]) downloadingDataWithName:[favorite songName] andArtist:[[ParserClass sharedItems] artistName] andDuration:[favorite durations] andImage:[[ParserClass sharedItems] imgAlbum] andPrice:[favorite price] andSongID:[favorite songID] andAlbumName:[[ParserClass sharedItems] albumName] andSongLyrics:nil];
                        
                        [((AppDelegate*)[[UIApplication sharedApplication] delegate]) fetchDownloadingDataFromCoreData];
                        
                    }
                    
                    
                }
        
       

        
        
    }else{
    
        NSLog(@"Cancel Download");
        
    }
        
    }else if (alertView.tag == 2){
    
    if (buttonIndex == 0) {
        
        NSMutableDictionary *dictData = [NSMutableDictionary dictionary];
        
        UserDetails *user = [[ParserClass sharedItems] userDetails][0];
        NSInteger idx = [[ParserClass sharedItems] idxCount];
        Songs *song = [[ParserClass sharedItems] songDetails][idx];
        
        TopDownloaded *topDL = [[ParserClass sharedItems] topDownloadeds][idx];
        
        Favorites *favorite = [[ParserClass sharedItems] topFavorites][idx];
        
        
        if (!(song == nil)) {
         [dictData setObject:[song idSong] forKey:@"song_id"];
            
        }else if (!(topDL == nil)){
            [dictData setObject:[topDL songID] forKey:@"song_id"];
        
        }else if (!(favorite == nil)){
        
            [dictData setObject:[favorite songID] forKey:@"song_id"];
        }
        
        [dictData setObject:[user idUser] forKey:@"user_id"];
       
        [dictData setObject:[alertView textFieldAtIndex:0].text forKey:@"comment"];
        //    [dictData setObject:@"5" forKey:@"rate"];
        
        //    song_id=%@&user_id=%@&rate=%@
        
        dispatch_async(kBgQueue, ^{
            
            NSData* data = [[PostClass sharedItems] commentsPost:dictData];
            
            [self performSelectorOnMainThread:@selector(fetchedDataComments:)
                                   withObject:data waitUntilDone:YES];
            
        });
        
        [self commentLoading];
        
        [self.tblComment reloadData];
        
       
    }else{
        
    
        NSLog(@"Cancel Comment");
    }
        
    }else if (alertView.tag == 3){
    
    if (buttonIndex == 0) {
        
        //NSString *ratesFromComment =  rateData.text;
        
        NSMutableDictionary *dictData = [NSMutableDictionary dictionary];
        NSInteger idx = [[ParserClass sharedItems] idxCount];
        UserDetails *user = [[ParserClass sharedItems] userDetails][0];
        Songs *song = [[ParserClass sharedItems] songDetails][idx];
        TopDownloaded *topDL = [[ParserClass sharedItems] topDownloadeds][idx];
        
        Favorites *favorite = [[ParserClass sharedItems] topFavorites][idx];
        
        if (!(song == nil)) {
            [dictData setObject:[song idSong] forKey:@"song_id"];
            
        }else if (!(topDL == nil)){
             
            [dictData setObject:[topDL songID] forKey:@"song_id"];
            
        }else if (!(favorite == nil)){
            
            [dictData setObject:[favorite songID] forKey:@"song_id"];
        }
        
        [dictData setObject:[user idUser] forKey:@"user_id"];
//        [dictData setObject:[song idSong] forKey:@"song_id"];
        [dictData setObject:[alertView textFieldAtIndex:0].text forKey:@"rate"];
        
        //    song_id=%@&user_id=%@&rate=%@
        
        dispatch_async(kBgQueue, ^{
            
            NSData* data = [[PostClass sharedItems] rateSongs:dictData];
            
            [self performSelectorOnMainThread:@selector(fetchedData:)
                                   withObject:data waitUntilDone:YES];
            
            
            
        });
        
       
        
    }else{
    
        NSLog(@"Cancel Rate");
    }
        
    }

}

- (IBAction)playDownloaded:(id)sender {
    
    NSLog(@"Play");
    
    DownloadedSongs *dlSongs = [[ParserClass sharedItems] downloadedSongs][0];

    
    [self playAudioFromData:[dlSongs songData]];

}

- (IBAction)rateAction:(id)sender {
    
    NSLog(@"Rate");
    
}

- (IBAction)likeAction:(id)sender {
    
    NSLog(@"Like");
    
    [self.likeBtn setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
    NSMutableDictionary *dictData = [NSMutableDictionary dictionary];
    
    UserDetails *user = [[ParserClass sharedItems] userDetails][0];
    NSInteger idx = [[ParserClass sharedItems] idxCount];
    Songs *song = [[ParserClass sharedItems] songDetails][idx];
    
    TopDownloaded *topDL = [[ParserClass sharedItems] topDownloadeds][idx];
    
    Favorites *favorite = [[ParserClass sharedItems] topFavorites][idx];
    
    if (!(song == nil)) {
        [dictData setObject:[song idSong] forKey:@"song_id"];
        
    }else if (!(topDL == nil)){
        [dictData setObject:[topDL songID] forKey:@"song_id"];
        
    }else if (!(favorite == nil)){
        
        [dictData setObject:[favorite songID] forKey:@"song_id"];
    }
    
    [dictData setObject:[user idUser] forKey:@"user_id"];
    
    dispatch_async(kBgQueue, ^{
        
        NSData* data = [[PostClass sharedItems] likeSongs:dictData];
        
        [self performSelectorOnMainThread:@selector(fetchedDataLikes:)
                               withObject:data waitUntilDone:YES];
       
        
        
    });
    
    
}

- (IBAction)postAction:(id)sender {
    
    UIAlertView *av = [[UIAlertView alloc]initWithTitle:@"Comment" message:@"Please enter your comment" delegate:self cancelButtonTitle:nil otherButtonTitles:@"Post",@"Cancel", nil];
    av.alertViewStyle = UIAlertViewStylePlainTextInput;
    //[av textFieldAtIndex:0].delegate = self;
    av.tag = 2;
    [av show];
    
}

-(void)destiActiom:(id)sender{
    NSLog(@"ajksdjkahdjaksdhkja");
}



- (void)fetchedDataComments:(NSData *)responseData {
    
    NSDictionary *json = [JsonClass jsonParser:responseData];
    
    //    [[ParserClass sharedItems] artistDetails:json];
    //
    //    [self.tableView reloadData];
    
    NSLog(@"comment data = %@", json);
}

- (void)fetchedData:(NSData *)responseData {
    
    NSDictionary *json = [JsonClass jsonParser:responseData];
    
//    [[ParserClass sharedItems] artistDetails:json];
//    
//    [self.tableView reloadData];
    
    if ([[json objectForKey:@"status"] isEqualToString:@"Success"]) {
         NSLog(@"rate data  = %@", json);
        
        //rateData = [av textFieldAtIndex:0];
        
//        numberOfrate = rateData.text;
//        
//        
//        int rating = numberOfrate.intValue;
//        
//        StarRatingView* starViewNoLabel = [[StarRatingView alloc]initWithFrame:CGRectMake(55, 421, 45, 8) andRating:rating withLabel:NO animated:YES];
//        
//        [starViewNoLabel setUserInteractionEnabled:NO];
//        
//        NSLog(@"New Rating Value = %i", rating);
//        
//        [self.view addSubview:starViewNoLabel];

        
        //NSLog(@"Winner = %@", numberOfrate);
    }
    
}

- (void)fetchedDataLikes:(NSData *)responseData {
    
    NSDictionary *json = [JsonClass jsonParser:responseData];
    
    //    [[ParserClass sharedItems] artistDetails:json];
    //
    //    [self.tableView reloadData];
    
    
    NSLog(@"rate data = %@", json);
    
    if ([[json objectForKey:@"status"] isEqualToString:@"Failed"] ) {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Failed" message:@"You have already liked this song." delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil, nil];
        
        [alert show];
        
    }else{
        
        Songs *song = [[ParserClass sharedItems] songDetails][[[ParserClass sharedItems] idxCount]];
        self.likeCount.text = [NSString stringWithFormat:@"%i", [[song likes] intValue] + 1];
        [self.likeBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    }
}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    
    [_handle seekToEndOfFile];
    [_handle writeData:data];
    
    
    
    if (connection == theConnection)
    {
        [receivedData appendData:data];
        
        float b = receivedData.length;
        
        
        float a = (b / [[[ParserClass sharedItems] fileSizeSong] floatValue]) * 100;
        
        double val = (double) a / 100;
        
        [NSByteCountFormatter stringFromByteCount:receivedData.length countStyle:NSByteCountFormatterCountStyleFile];

        
        [self.largeProgressIndicator setValue:val];
    
        
        NSLog(@"connection data %@ %f", [connection.currentRequest URL], val);
   
        
        
        
    }
}




- (void) playAudioFromData: (NSData*) data {
    NSError *error = nil;
    
    LocalPlayerClass *lp = [LocalPlayerClass sharedItems];
    
//    player=[[AVAudioPlayer alloc]initWithContentsOfURL:url error:NULL];
//    player.delegate=self;
//    [player play];
    lp.audioPlayer = [[AVAudioPlayer alloc] initWithData:data error:&error];
    lp.audioPlayer.delegate = self;
    [lp.audioPlayer prepareToPlay];
    [lp.audioPlayer play];
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{

    NSLog(@"finish");
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//    [connection setDelegateQueue:[NSOperationQueue currentQueue]];
    
    if (connection == theConnection)
    {
        
//        [self checkQueue];

        NSLog(@"Final Kilobytes %@",[NSByteCountFormatter stringFromByteCount:receivedData.length countStyle:NSByteCountFormatterCountStyleFile]);

        
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        //    NSInteger theHighScore =
        
        NSInteger idx = [defaults integerForKey:@"idxData"];
        
        // [[ParserClass sharedItems] idxCount];
        
        NSLog(@"downloadqueue = %@", self.downloadQueue);
        
      
        
//        [[ParserClass sharedItems] downloadingDatas];
        
        UserDetails *userDetails = [[ParserClass sharedItems] userDetails][0];
        
 
        
        if (!(receivedData == nil)) {
            
    
            NSLog(@"Count Confirmed");
            
            NSDictionary *dictData = [[PostClass sharedItems] downloadCount:[[[[ParserClass sharedItems] downloadingDatas] objectAtIndex:0] objectForKey:@"songID"] andUserID:[userDetails idUser] andPrice:[[[[ParserClass sharedItems] downloadingDatas] objectAtIndex:0] objectForKey:@"price"] andUserCredits:[userDetails credits] andAlbumID:[[ParserClass sharedItems] albumID]];
            
            
            if ([[dictData objectForKey:@"status"] isEqualToString:@"Success"]) {
                
                [((AppDelegate*)[[UIApplication sharedApplication] delegate]) musicDataWithName:[[[[ParserClass sharedItems] downloadingDatas] objectAtIndex:0] objectForKey:@"songTitle"] andData:receivedData andSongID:[[[[ParserClass sharedItems] downloadingDatas] objectAtIndex:0] objectForKey:@"songID"] andImage:[[[[ParserClass sharedItems] downloadingDatas] objectAtIndex:0] objectForKey:@"img"] andDuration:[[[[ParserClass sharedItems] downloadingDatas] objectAtIndex:0] objectForKey:@"duration"] andArtistName:[[[[ParserClass sharedItems] downloadingDatas] objectAtIndex:0] objectForKey:@"artistName"] anduserID:[userDetails idUser] andAlbumName:[[[[ParserClass sharedItems] downloadingDatas] objectAtIndex:0] objectForKey:@"albumName"] andSongLyrics:[[[[ParserClass sharedItems] downloadingDatas] objectAtIndex:0] objectForKey:@"lyrics"]];
                
                [((AppDelegate*)[[UIApplication sharedApplication] delegate]) deleteDownloadingData:0];
                [((AppDelegate*)[[UIApplication sharedApplication] delegate]) fetchDownloadingDataFromCoreData];
                
                [[NSNotificationCenter defaultCenter] postNotificationName:@"userProfile" object:@"userProfile"];
                 
                
                
                
//                [((AppDelegate*)[[UIApplication sharedApplication] delegate]) playListArtistName:[[[[ParserClass sharedItems] downloadingDatas] objectAtIndex:0] objectForKey:@"artistName"] andAlbumName:[[[[ParserClass sharedItems] downloadingDatas] objectAtIndex:0] objectForKey:@"albumName"]];
//                
//                [((AppDelegate*)[[UIApplication sharedApplication] delegate]) fetchPlayListDataFromCoreData];
                
                
                //                    UIAlertView *success = [[UIAlertView alloc]initWithTitle:@"Success" message:@"Download Complete" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                
                //                    [success show];
                
//                for (int i = 0; i < [[[ParserClass sharedItems] playListData] count]; i++) {
//                    
//                    PlayListData *playListData = [[ParserClass sharedItems] playListData][i];
//                    
//                    if ([[playListData artistName] isEqualToString:[[[[ParserClass sharedItems] downloadingDatas] objectAtIndex:0] objectForKey:@"artistName"]] || [[playListData albumName] isEqualToString:[[[[ParserClass sharedItems] downloadingDatas] objectAtIndex:0] objectForKey:@"albumName"]]) {
//                    
//                        NSLog(@"Duplicate Record");
//                        
//                    }else{
//                    
//                        [((AppDelegate*)[[UIApplication sharedApplication] delegate]) playListArtistName:[[[[ParserClass sharedItems] downloadingDatas] objectAtIndex:0] objectForKey:@"artistName"] andAlbumName:[[[[ParserClass sharedItems] downloadingDatas] objectAtIndex:0] objectForKey:@"albumName"]];
//                        
//                        [((AppDelegate*)[[UIApplication sharedApplication] delegate]) fetchPlayListDataFromCoreData];
//                        
//                        
//                    }
//                    
//                }
                
            }
            
            else{
                
                UIAlertView *success = [[UIAlertView alloc]initWithTitle:@"Failed" message:@"Download Failed" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                
                [success show];
                
                
            }
            
            
       
//
//            if ([[[ParserClass sharedItems] type] isEqualToString:@"Songs"]) {
//                
////                     for (int i = 0; i < [[[ParserClass sharedItems] downloadingDatas] count]; i++) {
//                
//                NSDictionary *dictData = [[PostClass sharedItems] downloadCount:[[[[ParserClass sharedItems] downloadingDatas] objectAtIndex:0] objectForKey:@"songID"] andUserID:[userDetails idUser] andPrice:[[[[ParserClass sharedItems] downloadingDatas] objectAtIndex:0] objectForKey:@"price"] andUserCredits:[userDetails credits]];
//                
//                
//                if ([[dictData objectForKey:@"status"] isEqualToString:@"Success"]) {
//                    
//                    [((AppDelegate*)[[UIApplication sharedApplication] delegate]) musicDataWithName:[[[[ParserClass sharedItems] downloadingDatas] objectAtIndex:0] objectForKey:@"songTitle"] andData:receivedData andSongID:[[[[ParserClass sharedItems] downloadingDatas] objectAtIndex:0] objectForKey:@"songID"] andImage:[[[[ParserClass sharedItems] downloadingDatas] objectAtIndex:0] objectForKey:@"img"] andDuration:[[[[ParserClass sharedItems] downloadingDatas] objectAtIndex:0] objectForKey:@"duration"] andArtistName:[[[[ParserClass sharedItems] downloadingDatas] objectAtIndex:0] objectForKey:@"artistName"] anduserID:[userDetails idUser]];
//                    
//                    [((AppDelegate*)[[UIApplication sharedApplication] delegate]) deleteDownloadingData:0];
//                     [((AppDelegate*)[[UIApplication sharedApplication] delegate]) fetchDownloadingDataFromCoreData];
////                    UIAlertView *success = [[UIAlertView alloc]initWithTitle:@"Success" message:@"Download Complete" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
//                    
////                    [success show];
//                }
//                
//                else{
//                    
//                    UIAlertView *success = [[UIAlertView alloc]initWithTitle:@"Failed" message:@"Download Failed" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
//                    
//                    [success show];
//                    
//                    
//                }
////                     }
//                
//                
//                
//                
//            }else if ([[[ParserClass sharedItems] type] isEqualToString:@"TopDownloads"]){
//                
//                NSDictionary *dictData = [[PostClass sharedItems] downloadCount:[[[[ParserClass sharedItems] downloadingDatas] objectAtIndex:0] objectForKey:@"songID"] andUserID:[userDetails idUser] andPrice:[[[[ParserClass sharedItems] downloadingDatas] objectAtIndex:0] objectForKey:@"price"] andUserCredits:[userDetails credits]];
//                
//                
//                if ([[dictData objectForKey:@"status"] isEqualToString:@"Success"]) {
//                    
//                    [((AppDelegate*)[[UIApplication sharedApplication] delegate]) musicDataWithName:[[[[ParserClass sharedItems] downloadingDatas] objectAtIndex:0] objectForKey:@"songTitle"] andData:receivedData andSongID:[[[[ParserClass sharedItems] downloadingDatas] objectAtIndex:0] objectForKey:@"songID"] andImage:[[[[ParserClass sharedItems] downloadingDatas] objectAtIndex:0] objectForKey:@"img"] andDuration:[[[[ParserClass sharedItems] downloadingDatas] objectAtIndex:0] objectForKey:@"duration"] andArtistName:[[[[ParserClass sharedItems] downloadingDatas] objectAtIndex:0] objectForKey:@"artistName"] anduserID:[userDetails idUser]];
//                    
//                    [((AppDelegate*)[[UIApplication sharedApplication] delegate]) deleteDownloadingData:0];
//                    [((AppDelegate*)[[UIApplication sharedApplication] delegate]) fetchDownloadingDataFromCoreData];
//                    //                    UIAlertView *success = [[UIAlertView alloc]initWithTitle:@"Success" message:@"Download Complete" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
//                    
//                    //                    [success show];
//                }
//                
//                else{
//                    
//                    UIAlertView *success = [[UIAlertView alloc]initWithTitle:@"Failed" message:@"Download Failed" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
//                    
//                    [success show];
//                    
//                    
//                }
//
//                
//            }else if ([[[ParserClass sharedItems] type] isEqualToString:@"Favorites"]){
//                NSDictionary *dictData = [[PostClass sharedItems] downloadCount:[[[[ParserClass sharedItems] downloadingDatas] objectAtIndex:0] objectForKey:@"songID"] andUserID:[userDetails idUser] andPrice:[[[[ParserClass sharedItems] downloadingDatas] objectAtIndex:0] objectForKey:@"price"] andUserCredits:[userDetails credits]];
//                
//                
//                if ([[dictData objectForKey:@"status"] isEqualToString:@"Success"]) {
//                    
//                    [((AppDelegate*)[[UIApplication sharedApplication] delegate]) musicDataWithName:[[[[ParserClass sharedItems] downloadingDatas] objectAtIndex:0] objectForKey:@"songTitle"] andData:receivedData andSongID:[[[[ParserClass sharedItems] downloadingDatas] objectAtIndex:0] objectForKey:@"songID"] andImage:[[[[ParserClass sharedItems] downloadingDatas] objectAtIndex:0] objectForKey:@"img"] andDuration:[[[[ParserClass sharedItems] downloadingDatas] objectAtIndex:0] objectForKey:@"duration"] andArtistName:[[[[ParserClass sharedItems] downloadingDatas] objectAtIndex:0] objectForKey:@"artistName"] anduserID:[userDetails idUser]];
//                    
//                    [((AppDelegate*)[[UIApplication sharedApplication] delegate]) deleteDownloadingData:0];
//                    [((AppDelegate*)[[UIApplication sharedApplication] delegate]) fetchDownloadingDataFromCoreData];
//                    //                    UIAlertView *success = [[UIAlertView alloc]initWithTitle:@"Success" message:@"Download Complete" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
//                    
//                    //                    [success show];
//                }
//                
//                else{
//                    
//                    UIAlertView *success = [[UIAlertView alloc]initWithTitle:@"Failed" message:@"Download Failed" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
//                    
//                    [success show];
//                    
//                    
//                }
//                
//            }
            
           
            
            // Album *album = [[ParserClass sharedItems] albumDetails][idx];
        
        }
        
        [_handle closeFile];
        
    }
    
}



#pragma mark - Image Load method

-(void)setImageString:(NSString *)strImage{
    [NSThread detachNewThreadSelector:@selector(showImage:) toTarget:self withObject:strImage];
}

-(void)showImage:(NSString*)imageShow{
    @autoreleasepool {
        NSData *imageList = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageShow]];
        [self.imgAlbum setAlpha:0];
        [UIView animateWithDuration:0.5 animations:^{
            
            self.imgAlbum.image = [UIImage imageWithData:imageList];
            [self.actLoading setHidden:YES];
            [self.imgAlbum setAlpha:1];
        } completion:^(BOOL finished) {
            
        }];
        
        
        //[self animationActivity];
    }
}

- (IBAction)backAction:(id)sender {
    
    [[AudioPlayManager shareObject] stop];
    
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)btnRatings:(id)sender {
    
    NSLog(@"Rate");
    UIAlertView *av = [[UIAlertView alloc]initWithTitle:@"Rate" message:@"Please rate by 1 - 5" delegate:self cancelButtonTitle:nil otherButtonTitles:@"Rate",@"Cancel", nil];
    av.alertViewStyle = UIAlertViewStylePlainTextInput;
    //[av textFieldAtIndex:0].delegate = self;
    
    //UITextField *testField =  [av textFieldAtIndex: 0];
    
    rateData = [av textFieldAtIndex:0];
    
    numberOfrate = rateData.text;
    
    
    av.tag = 3;
    [av show];
}

- (IBAction)btnShare:(id)sender {
}




#pragma mark - UITextField Delegate

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    [textField resignFirstResponder];
    
    return YES;
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return [[[ParserClass sharedItems] songComments] count];
    //[[[ParserClass sharedItems] schedules] count];
    //[[[ParserClass sharedItems] songDetails] count];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Configure the cell...
    
    static NSString *cellIdentifier = @"Cell";
    
    PlaySongTableViewCell *cell = (PlaySongTableViewCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (cell == nil) {
        
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"PlaySongTableViewCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
        
    }
    
    Comments *comment = [[ParserClass sharedItems] songComments][indexPath.row];
    
    cell.nameLbl.text = [comment name];
    cell.commentTxt.text = [comment comment];
    [cell setImageString:[NSString stringWithFormat:@"http://192.185.93.102/~boomeran/backend-panel/%@", [comment img]]];

    cell.lblDate.text = [comment date];

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    [cell.lblTime setText:[comment time]];
    
    return cell;
    
}





#pragma mark - OG;

// You need to override loginView:handleError in order to handle possible errors that can occur during login
- (void)loginView:(FBLoginView *)loginView handleError:(NSError *)error {
    NSString *alertMessage, *alertTitle;
    
    // If the user should perform an action outside of you app to recover,
    // the SDK will provide a message for the user, you just need to surface it.
    // This conveniently handles cases like Facebook password change or unverified Facebook accounts.
    if ([FBErrorUtility shouldNotifyUserForError:error]) {
        alertTitle = @"Facebook error";
        alertMessage = [FBErrorUtility userMessageForError:error];
        
        // This code will handle session closures since that happen outside of the app.
        // You can take a look at our error handling guide to know more about it
        // https://developers.facebook.com/docs/ios/errors
    } else if ([FBErrorUtility errorCategoryForError:error] == FBErrorCategoryAuthenticationReopenSession) {
        alertTitle = @"Session Error";
        alertMessage = @"Your current session is no longer valid. Please log in again.";
        
        // If the user has cancelled a login, we will do nothing.
        // You can also choose to show the user a message if cancelling login will result in
        // the user not being able to complete a task they had initiated in your app
        // (like accessing FB-stored information or posting to Facebook)
    } else if ([FBErrorUtility errorCategoryForError:error] == FBErrorCategoryUserCancelled) {
        NSLog(@"user cancelled login");
        
        // For simplicity, this sample handles other errors with a generic message
        // You can checkout our error handling guide for more detailed information
        // https://developers.facebook.com/docs/ios/errors
    } else {
        alertTitle  = @"Something went wrong";
        alertMessage = @"Please try again later.";
        NSLog(@"Unexpected error:%@", error);
    }
    
    if (alertMessage) {
        [[[UIAlertView alloc] initWithTitle:alertTitle
                                    message:alertMessage
                                   delegate:nil
                          cancelButtonTitle:@"OK"
                          otherButtonTitles:nil] show];
    }
}



- (IBAction)shareLinkWithShareDialog:(id)sender
{
    
    // Check if the Facebook app is installed and we can present the share dialog
    FBLinkShareParams *params = [[FBLinkShareParams alloc] init];
    params.link = [NSURL URLWithString:@"http://192.185.2.177/~tapdash/projects/musicapp/"];
    
    
    // If the Facebook app is installed and we can present the share dialog
    if ([FBDialogs canPresentShareDialogWithParams:params]) {
        
        // Present share dialog
        
        NSLog(@"Facebook App Installed");
        
        [FBDialogs presentShareDialogWithLink:params.link
                                      handler:^(FBAppCall *call, NSDictionary *results, NSError *error) {
                                          if(error) {
                                              // An error occurred, we need to handle the error
                                              // See: https://developers.facebook.com/docs/ios/errors
                                              NSLog(@"Error publishing story: %@", error.description);
                                          } else {
                                              // Success
                                              NSLog(@"result %@", results);
                                          }
                                      }];
        
        
        
        
        
        
        
        // If the Facebook app is NOT installed and we can't present the share dialog
    } else {
        // FALLBACK: publish just a link using the Feed dialog
        
        NSLog(@"Facebook App Not Installed");
        
        // Put together the dialog parameters
        
        NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                       @"Boomerang!", @"name",
                                       @"Please Download.", @"caption",
                                       @"For Indie Bands", @"description",
                                       @"http://192.185.2.177/~tapdash/", @"link",
                                       @"http://pedigreedogtales.com/images/boomerang_logo.png", @"picture",
                                       nil];
        
        // Show the feed dialog
        [FBWebDialogs presentFeedDialogModallyWithSession:nil
                                               parameters:params
                                                  handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
                                                      if (error) {
                                                          // An error occurred, we need to handle the error
                                                          // See: https://developers.facebook.com/docs/ios/errors
                                                          NSLog(@"Error publishing story: %@", error.description);
                                                      } else {
                                                          if (result == FBWebDialogResultDialogNotCompleted) {
                                                              // User canceled.
                                                              NSLog(@"User cancelled.");
                                                          } else {
                                                              // Handle the publish feed callback
                                                              NSDictionary *urlParams = [self parseURLParams:[resultURL query]];
                                                              
                                                              if (![urlParams valueForKey:@"post_id"]) {
                                                                  // User canceled.
                                                                  NSLog(@"User cancelled.");
                                                                  
                                                              } else {
                                                                  // User clicked the Share button
                                                                  NSString *result = [NSString stringWithFormat: @"Posted story, id: %@", [urlParams valueForKey:@"post_id"]];
                                                                  NSLog(@"result %@", result);
                                                              }
                                                          }
                                                      }
                                                  }];
        
        
    }
}



// A function for parsing URL parameters returned by the Feed Dialog.
- (NSDictionary*)parseURLParams:(NSString *)query {
    NSArray *pairs = [query componentsSeparatedByString:@"&"];
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    for (NSString *pair in pairs) {
        NSArray *kv = [pair componentsSeparatedByString:@"="];
        NSString *val =
        [kv[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        params[kv[0]] = val;
    }
    return params;
}




@end
